import { service } from './service'

import { config } from './config'
import { postError } from '@/api'
import hash from 'hash-it'

import {errorsStore} from '@/store/errors'
const { default_headers } = config

const request = (option: any) => {
  const { url, method, params, data, headers, responseType, ...config } = option

  return service({
    url,
    method,
    data: params,
    ...config,
    responseType: responseType,
    headers
  }).catch((e) => {

    const store = errorsStore()
    store.init()

    const stack = e.stack;
    const error_name = e.toString()
    
    const _hash = hash(e)
    if(store.add(_hash)){
    
      postError(error_name,url,stack).then(res=>{

        debugger
      })
    }

    console.error(e)
    

    // uni.showToast({
    //   title:'服务器开小差了，请稍后再试',
    //   duration:4000,
    //   icon:'error'
    // })
    return Promise.reject(e)
  })
}
export default {
  get: async <T = any>(option: any) => {
    const res = await request({ method: 'GET', ...option })
    return res.data as unknown as T
  },
  post: async <T = any>(option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res.data as unknown as T
  },
  postOriginal: async (option: any) => {
    const res = await request({ method: 'POST', ...option })
    return res
  },
  delete: async <T = any>(option: any) => {
    const res = await request({ method: 'DELETE', ...option })
    return res.data as unknown as T
  },
  put: async <T = any>(option: any) => {
    const res = await request({ method: 'PUT', ...option })
    return res.data as unknown as T
  },
  download: async <T = any>(option: any) => {
    const res = await request({
      method: 'GET',
      responseType: 'blob',
      ...option
    })
    return res as unknown as Promise<T>
  },
  upload: async <T = any>(option: any) => {
    option.headersType = 'multipart/form-data'
    const res = await request({ method: 'POST', ...option })
    return res as unknown as Promise<T>
  }
}
